package getsubs.filenameguesser;

import getsubs.model.*;
import org.hamcrest.text.pattern.Parse;
import org.hamcrest.text.pattern.PatternMatchException;
import org.hamcrest.text.pattern.PatternMatcher;

public class RegExpGuesser implements EpisodeInfoGuesser {

    private static final PatternMatcher parser = new PatternMatcher(
            RegExpGuesserPatterns.filename());

    public EpisodeInfo guessFromFilename(String filename)
        throws Unguessable
    {
        try {
            return new GuessedEpisodeInfo(parser.parse(filename));
        } catch (PatternMatchException ex) {
            throw (Unguessable) new Unguessable(filename).initCause(ex);
        }
    }

    private static class GuessedEpisodeInfo implements EpisodeInfo{

        private final Parse parseResult;

        public GuessedEpisodeInfo(Parse parseResult) {
            this.parseResult = parseResult;
        }

        public String getShowName() {
            return parseResult.get("showname");
        }

        public String getEpisode() {
            return normalize(parseResult.get("episode"));
        }

        public String getSeason() {
            return normalize(parseResult.get("season"));
        }

        private String normalize(String text) {
            return "" + Integer.parseInt(text, 10);
        }
    }
}
